import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import qs from 'qs'
// import { getToken, getId } from '@/utils/auth'
import { showMessage } from './status'
const windown = window
const successCodes = [0, 200, undefined]
// create an axios instance
const service = axios.create({
  baseURL: '/api', // 线上
  timeout: 60000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (config.isImport) {
      config.headers['Content-Type'] = 'multipart/form-data'
    }
    else {
      // if(config.bodyType&&config.bodyType=='row'){
      //   config.data=JSON.stringify(config.data);
      //   config.headers['Content-Type'] = 'application/json'
      // }
      // else{
      //   config.data = qs.stringify(config.data)
      //   config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
      // }
      config.data = qs.stringify(config.data)
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
      // config.headers['Content-Type'] = 'application/json'
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
service.interceptors.response.use(
  response => {
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (!successCodes.includes(res.code)) {
      Message({
        message: res.msg || res.message || '非法请求',
        type: 'error',
        duration: 5 * 1000
      })
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 403) {
        // to re-login
        Message({
          message: '登陆过期',
          type: 'error',
          duration: 5 * 1000
        })
        store.dispatch('user/resetToken').then(() => {
          location.reload()
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    const { response } = error
    const message = showMessage(response.status)
    if (response.status === 401) {
      // windown.location.href = '/#/login'
      // Message({
      //   message: message,
      //   type: 'error',
      //   duration: 3 * 1000
      // })
    } else if (response.status === 500) {
      if (response.data && response.data.message) {
        Message({
          type: 'error',
          dangerouslyUseHTMLString: true,
          message: response.data.message,
          duration: 8 * 1000
        });
      }

    } else if (response) {
      Message({
        message: message,
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(message))
    } else {
      Message({
        message: '网络连接异常,请稍后再试!',
        type: 'error',
        duration: 5 * 1000
      })
    }
  }
)

export default service
